<template>
  <div class="app-container">
    <el-row :gutter="10" class="h-100">
      <!-- 左侧公海池分类 -->
      <el-col :span="3" class="h-100">
        <div class="left-panel">
          <div class="panel-title">
            <i class="el-icon-collection"></i>
            公海池分类
          </div>
          <div class="panel-content">
            <el-menu
              :default-active="activePool"
              class="pool-menu"
              @select="handlePoolSelect"
            >
              <el-menu-item 
                v-for="dict in dict.type.pool_type" 
                :key="dict.value" 
                :index="dict.value"
                class="pool-menu-item"
              >
                <div class="menu-item-content">
                  <div class="menu-item-left">
                    <i :class="['menu-item-icon', getPoolIcon(dict.value)]"></i>
                    <span class="menu-item-label">{{ dict.label }}</span>
                  </div>
                  <el-tag 
                    v-if="poolCounts[dict.value]" 
                    size="small" 
                    :type="getPoolTagType(dict.value)"
                    class="pool-count"
                  >
                    {{ poolCounts[dict.value] || 0 }}
                  </el-tag>
                </div>
              </el-menu-item>
            </el-menu>
          </div>
        </div>
      </el-col>

      <!-- 右侧内容区 -->
      <el-col :span="21" class="h-100">
        <div class="right-panel">
          <!-- 添加滚动容器 -->
          <div class="scroll-container">
            <!-- 时间统计区域 -->
            <div class="statistics-section" v-if="!activePool">
              <!-- 时间段统计卡片 -->
              <el-card shadow="hover" class="statistics-card">
                <div class="statistics-header">
                  <div class="left-section">
                    <span class="statistics-title">
                      <i class="el-icon-data-analysis"></i>
                      数据统计
                    </span>
                    <el-radio-group v-model="timeRange" size="small" @change="handleTimeRangeChange">
                      <el-radio-button label="week">本周</el-radio-button>
                      <el-radio-button label="month">本月</el-radio-button>
                      <el-radio-button label="quarter">本季度</el-radio-button>
                      <el-radio-button label="year">本年</el-radio-button>
                      <el-radio-button label="custom">自定义</el-radio-button>
                    </el-radio-group>
                  </div>
                  <div class="right-section" v-if="timeRange === 'custom'">
                    <el-date-picker
                      v-model="customDateRange"
                      type="daterange"
                      range-separator="至"
                      start-placeholder="开始日期"
                      end-placeholder="结束日期"
                      size="small"
                      value-format="yyyy-MM-dd"
                      @change="handleCustomDateChange"
                    />
                  </div>
                </div>
                <div class="statistics-body">
                  <el-row :gutter="20">
                    <el-col :span="12">
                      <div class="stat-card total-card">
                        <div class="stat-icon">
                          <i class="el-icon-user"></i>
                        </div>
                        <div class="stat-info">
                          <div class="stat-label">时间段内新增客户</div>
                          <div class="stat-value">{{ periodStats.total || 0 }}</div>
                          <div class="card-time-text" v-if="getTimeRangeText">{{ getTimeRangeText }}</div>
                        </div>
                      </div>
                    </el-col>
                    <el-col :span="12">
                      <div class="stat-card rate-card">
                        <div class="stat-icon">
                          <i class="el-icon-data-line"></i>
                        </div>
                        <div class="stat-info">
                          <div class="stat-label">日均新增</div>
                          <div class="stat-value">{{ getDailyAverage }}</div>
                          <div class="card-time-text" v-if="getTimeRangeText">{{ getTimeRangeText }}</div>
                        </div>
                      </div>
                    </el-col>
                  </el-row>
                </div>
              </el-card>

              <!-- 公海池类型统计卡片 -->
              <el-card shadow="hover" class="statistics-card" v-if="!activePool">
                <div class="statistics-header">
                  <span class="statistics-title">
                    <i class="el-icon-collection"></i>
                    公海池分类统计
                  </span>
                </div>
                <div class="statistics-body">
                  <el-row :gutter="20">
                    <el-col :span="8" v-for="dict in dict.type.pool_type" :key="dict.value">
                      <div :class="['pool-stat-card', getPoolCardClass(dict.value)]" @click="handlePoolSelect(dict.value)">
                        <div class="pool-stat-icon">
                          <i :class="getPoolIcon(dict.value)"></i>
                        </div>
                        <div class="pool-stat-info">
                          <div class="pool-stat-label">{{ dict.label }}</div>
                          <div class="pool-stat-value">{{ poolCounts[dict.value] || 0 }}</div>
                          <div class="pool-stat-desc">当前客户数量</div>
                        </div>
                      </div>
                    </el-col>
                  </el-row>
                </div>
              </el-card>
            </div>

            <!-- 搜索区域和客户列表 -->
            <template v-if="activePool">
              <div class="search-section">
                <el-form :model="queryParams" ref="queryForm" :inline="true" v-show="showSearch" size="mini" label-width="auto">
                  <el-form-item label="客户姓名" prop="customerName">
                    <el-input
                      v-model="queryParams.customerName"
                      placeholder="请输入客户姓名"
                      clearable
                      size="mini"
                      prefix-icon="el-icon-user"
                      @keyup.enter.native="handleQuery"
                      style="width: 120px"
                    />
                  </el-form-item>
                  <el-form-item label="联系电话" prop="contactPhone">
                    <el-input
                      v-model="queryParams.contactPhone"
                      placeholder="请输入联系电话"
                      clearable
                      size="mini"
                      prefix-icon="el-icon-phone"
                      @keyup.enter.native="handleQuery"
                      style="width: 120px"
                    />
                  </el-form-item>
                  <el-form-item>
                    <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
                    <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
                  </el-form-item>
                </el-form>
              </div>

              <div class="table-container">
                <!-- 表格区域 -->
                <el-table
                  v-loading="loading"
                  :data="casesList"
                  @selection-change="handleSelectionChange"
                  :header-cell-style="{ background: '#f8f8f9', color: '#606266', padding: '5px 0' }"
                  :cell-style="{ padding: '6px 0' }"
                  border
                  stripe
                  size="mini"
                  highlight-current-row
                  :height="tableHeight"
                  style="width: 100%"
                >
                  <el-table-column type="selection" min-width="40" align="center" />
                  <el-table-column label="案件编号" align="center" prop="caseId" min-width="80" show-overflow-tooltip />
                  <el-table-column label="客户姓名" align="center" prop="customerName" min-width="70" />
                  
                  <el-table-column label="身份证号" align="center" prop="idCardNumber" min-width="180" show-overflow-tooltip />
                  
                  <el-table-column label="诉讼/调解案号" align="center" prop="litigationMediationCaseNumber" min-width="150" show-overflow-tooltip>
                    <template slot-scope="scope">
                      <span>{{ scope.row.litigationMediationCaseNumber || '-' }}</span>
                    </template>
                  </el-table-column>
                  <el-table-column label="执行案号" align="center" prop="enforcementCaseNumber" min-width="150" show-overflow-tooltip>
                    <template slot-scope="scope">
                      <span>{{ scope.row.enforcementCaseNumber || '-' }}</span>
                    </template>
                  </el-table-column>
                  <el-table-column label="案件负责人" align="center" prop="caseHandler" min-width="100">
                    <template slot-scope="scope">
                      <el-tag size="mini" v-if="scope.row.caseHandler">{{ getUserLabel(scope.row.caseHandler) }}</el-tag>
                      <span v-else>-</span>
                    </template>
                  </el-table-column>
                  <el-table-column label="经办人" align="center" prop="handlerUser" min-width="90">
                    <template slot-scope="scope">
                      <el-tag size="mini" type="success" v-if="scope.row.handlerUser">{{ getUserLabel(scope.row.handlerUser) }}</el-tag>
                      <span v-else>-</span>
                    </template>
                  </el-table-column>
                  <el-table-column label="进入时间" align="center" prop="poolEntryTime" min-width="150" show-overflow-tooltip>
                    <template slot-scope="scope">
                      <span>{{ parseTime(scope.row.poolEntryTime) }}</span>
                    </template>
                  </el-table-column>
                  <el-table-column label="操作" align="center" class-name="small-padding fixed-width" min-width="80" fixed="right">
                    <template slot-scope="scope">
                      <el-button
                        size="mini"
                        type="text"
                        icon="el-icon-edit"
                        @click="handleUpdate(scope.row)"
                        v-hasPermi="['system:cases:edit']"
                      >修改</el-button>
                    </template>
                  </el-table-column>
                </el-table>

                <!-- 分页区域 -->
                <pagination
                  v-show="total>0"
                  :total="total"
                  :page.sync="queryParams.pageNum"
                  :limit.sync="queryParams.pageSize"
                  @pagination="getList"
                  class="pagination-container"
                  small
                  :page-sizes="[20, 50, 100, 200, 500, -1]"
                  :page-size-options="[{label: '20条/页', value: 20}, {label: '50条/页', value: 50}, {label: '100条/页', value: 100}, {label: '200条/页', value: 200}, {label: '500条/页', value: 500}, {label: '全部', value: -1}]"
                />
              </div>
            </template>
            <template v-else>
              <!-- 空状态提示 -->
            </template>
          </div>
        </div>
      </el-col>
    </el-row>

    <!-- 添加或修改客户信息对话框 -->
    <el-dialog :title="title" :visible.sync="open" width="900px" append-to-body>
      <div class="pool-exit-tip" v-if="form.poolType">
        <el-alert
          title="从公海池领取客户的方法"
          type="info"
          :closable="false"
          show-icon>
          <div>若要将客户从公海池领取出来，请设置<strong>案件负责人</strong>或<strong>经办人</strong>。设置后客户将显示在客户信息列表中。</div>
          <div v-if="!checkPermission(['system:pool:claim'])" class="permission-warning">
            <i class="el-icon-warning"></i> 您当前没有从公海领取客户的权限(system:pool:claim)，请联系管理员开通。
          </div>
        </el-alert>
      </div>
      <el-form ref="form" :model="form" :rules="rules" label-width="100px">
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="客户姓名" prop="customerName">
              <el-input v-model="form.customerName" placeholder="请输入客户姓名" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="联系电话" prop="contactPhone">
              <el-input v-model="form.contactPhone" placeholder="请输入联系电话" />
            </el-form-item>
          </el-col>
        </el-row>
        
        <!-- 关联人信息区域 -->
        <el-row :gutter="20">
          <el-col :span="24">
            <el-form-item label="关联人信息" prop="contactPersons">
              <div class="contact-persons-editor-simple">
                <div v-for="(person, index) in contactPersons" :key="index" class="contact-person-row">
                  <el-input v-model="person.name" placeholder="姓名" size="small" style="width: 32%; min-width: 100px;" />
                  <el-input v-model="person.phone" placeholder="联系方式" size="small" style="width: 32%; min-width: 100px; margin: 0 8px" />
                  <el-button type="text" icon="el-icon-delete" @click="removeContactPerson(index)" title="删除"></el-button>
                </div>
                <div class="add-contact-simple">
                  <el-button type="text" icon="el-icon-plus" @click="addContactPerson">添加关联人</el-button>
                </div>
              </div>
            </el-form-item>
          </el-col>
        </el-row>
        
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="身份证号码" prop="idCardNumber">
              <el-input v-model="form.idCardNumber" placeholder="请输入身份证号码" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="案件负责人" prop="caseHandler">
              <el-select 
                v-model="form.caseHandler" 
                placeholder="请选择案件负责人" 
                style="width: 100%"
                clearable
              >
                <el-option
                  v-for="item in userOptions"
                  :key="item.value"
                  :label="item.label"
                  :value="item.value"
                ></el-option>
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="经办人" prop="handlerUser">
              <el-select 
                v-model="form.handlerUser" 
                placeholder="请选择经办人" 
                style="width: 100%"
                filterable
                clearable
              >
                <el-option
                  v-for="item in userOptions"
                  :key="item.value"
                  :label="item.label"
                  :value="item.value"
                ></el-option>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="委托机构" prop="entrustingInstitution">
              <el-select v-model="form.entrustingInstitution" placeholder="请选择委托机构" style="width: 100%">
                <el-option
                  v-for="dict in dict.type.wtjg"
                  :key="dict.value"
                  :label="dict.label"
                  :value="dict.value"
                ></el-option>
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="债务类型" prop="debtType">
              <el-select v-model="form.debtType" placeholder="请选择债务类型" style="width: 100%">
                <el-option
                  v-for="dict in dict.type.zwlx"
                  :key="dict.value"
                  :label="dict.label"
                  :value="dict.value"
                ></el-option>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="诉讼/调解案号" prop="litigationMediationCaseNumber">
              <el-input v-model="form.litigationMediationCaseNumber" placeholder="请输入诉讼/调解案号" />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="执行案号" prop="enforcementCaseNumber">
              <el-input v-model="form.enforcementCaseNumber" placeholder="请输入执行案号" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="案件进度状态" prop="caseProgressStatus">
              <el-select v-model="form.caseProgressStatus" placeholder="请选择案件进度状态" style="width: 100%">
                <el-option
                  v-for="dict in dict.type.ajjdzt"
                  :key="dict.value"
                  :label="dict.label"
                  :value="dict.value"
                ></el-option>
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="公海类型" prop="poolType">
              <el-select v-model="form.poolType" placeholder="请选择公海类型" style="width: 100%" clearable>
                <el-option
                  v-for="dict in dict.type.pool_type"
                  :key="dict.value"
                  :label="dict.label"
                  :value="dict.value"
                ></el-option>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="案件进度说明" prop="caseProgressDescription">
              <el-input v-model="form.caseProgressDescription" type="textarea" :rows="3" placeholder="请输入内容" />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="24">
            <el-form-item label="文件" prop="fileInfo">
              <el-upload
                class="upload-demo"
                :action="upload.url"
                :headers="upload.headers"
                :on-success="handleUploadSuccess"
                :on-error="handleUploadError"
                :on-remove="handleFileRemove"
                :before-upload="handleBeforeUpload"
                :file-list="fileList"
                multiple>
                <el-button size="small" type="primary">点击上传</el-button>
                <div slot="tip" class="el-upload__tip">文件大小不超过500MB</div>
              </el-upload>
              <div v-if="form.fileInfo" class="existing-files">
                <div v-for="(file, index) in parsedFileList" :key="index" class="file-item">
                  <span class="file-name">{{ file.name }}</span>
                  <div class="file-actions">
                    <el-button
                      type="text"
                      size="mini"
                      icon="el-icon-download"
                      @click="handleDownload(file)"
                    >下载</el-button>
                    <el-button
                      type="text"
                      size="mini"
                      icon="el-icon-delete"
                      @click="handleFileDelete(index)"
                    >删除</el-button>
                  </div>
                </div>
              </div>
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import { listBankCustomerCases, getBankCustomerCases, addBankCustomerCases, updateBankCustomerCases } from "@/api/system/cases";
import { listUser } from "@/api/system/user";
import { getToken } from "@/utils/auth";

export default {
  name: "CustomerPool",
  dicts: ['pool_type', 'wtjg', 'zwlx', 'ajjdzt'],
  data() {
    return {
      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 案件表格数据
      casesList: [],
      // 当前选中的公海池类型
      activePool: '',
      // 各公海池数量统计
      poolCounts: {},
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 20,
        customerName: null,
        contactPhone: null,
        poolType: null,
        params: {
          needPoolCount: true
        },
        beginTime: null,
        endTime: null,
      },
      // 用户选项
      userOptions: [],
      // 时间统计相关
      timeRange: 'week',
      customDateRange: [],
      periodStats: {
        total: 0,
        poolDistribution: {}
      },
      showCustomerList: false, // 控制是否显示客户列表
      tableHeight: 'auto', // 表格高度
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      // 表单参数
      form: {
        caseId: null,
        customerName: null,
        contactPhone: null,
        idCardNumber: null,
        caseHandler: null,
        handlerUser: null,
        entrustingInstitution: null,
        debtType: null,
        litigationMediationCaseNumber: null,
        enforcementCaseNumber: null,
        caseProgressStatus: null,
        caseProgressDescription: null,
        fileInfo: null,
        poolType: null,
        poolEntryTime: null
      },
      // 表单校验
      rules: {
        customerName: [
          { required: true, message: "客户姓名不能为空", trigger: "blur" }
        ],
        poolType: [
          { required: false, trigger: "change" }
        ]
      },
      // 上传参数
      upload: {
        // 上传地址
        url: process.env.VUE_APP_BASE_API + "/system/cases/upload",
        // 请求头部
        headers: { Authorization: "Bearer " + getToken() }
      },
      // 文件列表
      fileList: [],
      parsedFileList: [], // 用于存储已解析的文件列表
      // 关联人列表
      contactPersons: [],
    };
  },
  computed: {
    getTimeRangeText() {
      const startDate = this.queryParams.beginTime;
      const endDate = this.queryParams.endTime;
      if (!startDate || !endDate) return '';
      
      return `${startDate} 至 ${endDate}`;
    },
    getDailyAverage() {
      if (!this.periodStats.total) return '0';
      const start = new Date(this.queryParams.beginTime);
      const end = new Date(this.queryParams.endTime);
      const days = Math.ceil((end - start) / (1000 * 60 * 60 * 24)) + 1;
      return (this.periodStats.total / days).toFixed(1);
    }
  },
  created() {
    // 初始化查询参数
    this.queryParams = {
      pageNum: 1,
      pageSize: 20,
      customerName: null,
      contactPhone: null,
      poolType: null,
      params: {
        needPoolCount: true
      }
    };

    // 获取用户列表（先于其他初始化操作）
    console.log('组件初始化，开始加载用户列表');
    this.getUsers();
    
    // 获取字典数据后立即获取统计数据
    this.getDicts("pool_type").then(() => {
      console.log('获取字典数据成功，开始获取统计数据');
      // 设置默认时间范围为本周
      this.timeRange = 'week';
      this.handleTimeRangeChange('week');
      // 获取统计数据
      this.getStatistics();
    }).catch(error => {
      console.error('获取公海池字典数据失败:', error);
    });
  },
  methods: {
    /** 获取统计数据 */
    getStatistics() {
      this.loading = true;
      const params = {
        pageNum: 1,
        pageSize: 1,
        beginTime: this.queryParams.beginTime,
        endTime: this.queryParams.endTime,
        params: {
          needPoolCount: true,
          needPeriodStats: true,
          beginTime: this.queryParams.beginTime,
          endTime: this.queryParams.endTime
        }
      };
      
      console.log('获取统计数据请求参数:', JSON.stringify(params));
      
      listBankCustomerCases(params).then(response => {
        console.log('获取统计数据响应:', JSON.stringify(response));
        
        // 处理公海池数量统计
        if (response && response.poolCounts) {
          const counts = {};
          if (Array.isArray(response.poolCounts)) {
            response.poolCounts.forEach(item => {
              if (item && item.key) {
                counts[item.key] = parseInt(item.value) || 0;
              }
            });
          } else if (typeof response.poolCounts === 'object') {
            Object.entries(response.poolCounts).forEach(([key, value]) => {
              counts[key] = parseInt(value) || 0;
            });
          }
          console.log('处理后的公海池数量:', counts);
          this.poolCounts = counts;
        }
        
        // 更新时间段统计
        if (response && response.periodStats) {
          let total = 0;
          const poolDistribution = {};
          
          console.log('原始时间段统计数据:', JSON.stringify(response.periodStats));
          
          // 处理时间段统计数据
          if (Array.isArray(response.periodStats)) {
            response.periodStats.forEach(item => {
              if (item && item.key) {
                const value = parseInt(item.value) || 0;
                poolDistribution[item.key] = value;
                total += value;
              }
            });
          } else if (typeof response.periodStats === 'object') {
            Object.entries(response.periodStats).forEach(([key, value]) => {
              const count = parseInt(value) || 0;
              poolDistribution[key] = count;
              total += count;
            });
          }
          
          this.periodStats = {
            total: total,
            poolDistribution: poolDistribution
          };
          
          console.log('更新后的时间段统计:', this.periodStats);
        } else {
          console.warn('未获取到时间段统计数据');
          this.periodStats = {
            total: 0,
            poolDistribution: {}
          };
        }
      }).catch(error => {
        console.error('获取统计数据失败:', error);
        this.$message.error('获取统计数据失败');
      }).finally(() => {
        this.loading = false;
      });
    },

    /** 获取列表数据 */
    getList() {
      if (!this.activePool) {
        return;
      }
      
      this.loading = true;
      console.log('获取客户列表参数:', {
        pageNum: this.queryParams.pageNum,
        pageSize: this.queryParams.pageSize,
        poolType: this.activePool,
        customerName: this.queryParams.customerName,
        contactPhone: this.queryParams.contactPhone
      });

      const params = {
        ...this.queryParams,
        poolType: this.activePool,
        pageNum: this.queryParams.pageNum,
        pageSize: this.queryParams.pageSize === -1 ? 10000 : (this.queryParams.pageSize || 20),
        params: {
          ...this.queryParams.params,
          needPoolCount: true,
          needPeriodStats: 'false'
        }
      };
      
      listBankCustomerCases(params).then(response => {
        console.log('获取客户列表响应:', response);
        if (response && response.rows) {
          this.casesList = response.rows;
          this.total = response.total;
          
          // 根据数据条数精确计算表格高度
          this.$nextTick(() => {
            if (this.casesList.length > 0) {
              // 每行高度约为37px，表头高度为40px，不额外预留空间
              this.tableHeight = this.casesList.length * 37 + 40;
              console.log('计算表格高度:', this.tableHeight);
            } else {
              this.tableHeight = 80; // 如果没有数据，只显示表头和一个空行
            }
          });
          
          // 客户列表时不覆盖池统计数据，避免浏览列表时覆盖首页统计
          // 移除更新公海池数量统计的代码
        } else {
          this.casesList = [];
          this.total = 0;
          this.tableHeight = 80;
        }
      }).catch(error => {
        console.error('获取客户列表失败:', error);
        this.casesList = [];
        this.total = 0;
        this.tableHeight = 80;
      }).finally(() => {
        this.loading = false;
      });
    },

    /** 搜索按钮操作 */
    handleQuery() {
      if (this.queryParams.customerName && this.queryParams.customerName.trim() !== '') {
        // 全局搜索客户姓名
        const params = {
          customerName: this.queryParams.customerName,
          pageNum: 1,
          pageSize: 10 // 可根据需要调整
        };
        listBankCustomerCases(params).then(response => {
          if (response && response.rows && response.rows.length > 0) {
            // 找到客户，切换到对应池
            const target = response.rows[0]; // 如有多个可弹窗选
            this.activePool = target.poolType;
            this.queryParams.poolType = target.poolType;
            this.queryParams.pageNum = 1;
            this.getList();
            // 可选：高亮/滚动到该客户
          } else {
            this.$message.info('未找到该客户');
          }
        });
        return;
      }
      // 没输入客户名，按原有逻辑
      if (!this.activePool) {
        this.$message.warning('请先选择公海池类型');
        return;
      }
      this.queryParams.pageNum = 1;
      this.getList();
    },

    /** 重置查询参数 */
    resetQuery() {
      this.resetForm("queryForm");
      this.queryParams.pageNum = 1;
      this.queryParams.pageSize = 20;
      if (this.activePool) {
        this.getList();
      }
    },

    /** 处理公海池选择 */
    handlePoolSelect(index) {
      console.log('选择公海池类型:', index);
      this.activePool = index;
      this.queryParams.poolType = index;
      this.queryParams.pageNum = 1;
      this.queryParams.pageSize = 20;
      this.getList();
    },

    /** 查询用户列表 */
    getUsers() {
      listUser({
        pageSize: 500, // 增加一次性获取的用户数量
        status: "0" // 获取所有正常状态的用户
      }).then(response => {
        if (response.code === 200) {
          this.userOptions = response.rows.map(item => ({
            value: item.userName,
            label: item.nickName
          }));
          console.log('获取用户数据成功，共加载用户数: ', this.userOptions.length);
        } else {
          console.error('获取用户数据失败:', response.msg);
        }
      }).catch(error => {
        console.error('获取用户列表失败:', error);
      });
    },

    /** 获取用户显示标签 */
    getUserLabel(userName) {
      if (!userName) return '';
      const user = this.userOptions.find(item => item.value === userName);
      return user ? user.label : userName;
    },

    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map(item => item.caseId)
      this.single = selection.length!==1
      this.multiple = !selection.length
    },

    /** 修改按钮操作 */
    handleUpdate(row) {
      this.reset();
      const caseId = row.caseId || this.ids;
      
      // 确保用户选项已加载
      if (this.userOptions.length === 0) {
        console.log('用户选项为空，重新加载用户列表');
        this.getUsers();
      } else {
        console.log('已加载的用户选项数量:', this.userOptions.length);
      }
      
      getBankCustomerCases(caseId).then(response => {
        if (response.code === 200) {
          const data = response.data;
          this.form = {
            ...data,
            poolType: data.poolType || null  // 确保正确加载公海类型
          };
          
          // 解析关联人信息
          if (this.isJsonArray(data.contactPersonName)) {
            this.contactPersons = this.parseContactPersons(data.contactPersonName, data.contactPersonPhone);
          } else if (data.contactPersonName) {
            // 处理旧数据格式
            this.contactPersons = [{
              name: data.contactPersonName || '',
              phone: data.contactPersonPhone || ''
            }];
          } else {
            this.contactPersons = [];
          }
          
          console.log('加载的客户信息:', this.form);
          console.log('案件负责人:', this.form.caseHandler);
          console.log('经办人:', this.form.handlerUser);
          console.log('可用的用户选项:', this.userOptions);
          
          this.updateParsedFileList();
          this.open = true;
          this.title = "修改客户信息";
        } else {
          this.$modal.msgError(response.msg || "获取客户信息失败");
        }
      }).catch(error => {
        console.error('获取客户信息失败:', error);
        this.$modal.msgError("获取客户信息失败，请重试");
      });
    },

    // 表单重置
    reset() {
      this.form = {
        caseId: null,
        customerName: null,
        contactPhone: null,
        idCardNumber: null,
        caseHandler: null,
        handlerUser: null,
        entrustingInstitution: null,
        debtType: null,
        litigationMediationCaseNumber: null,
        enforcementCaseNumber: null,
        caseProgressStatus: null,
        caseProgressDescription: null,
        fileInfo: null,
        poolType: null,
        poolEntryTime: null
      };
      // 清空文件列表
      this.fileList = [];
      this.parsedFileList = [];
      this.contactPersons = []; // 重置关联人信息
      this.resetForm("form");
    },

    // 取消按钮
    cancel() {
      this.open = false;
      this.reset();
    },

    /** 提交按钮 */
    submitForm() {
      this.$refs["form"].validate(valid => {
        if (valid) {
          // 检查是否设置了负责人或经办人
          const hasCaseHandler = this.form.caseHandler !== null && this.form.caseHandler !== '';
          const hasHandlerUser = this.form.handlerUser !== null && this.form.handlerUser !== '';
          
          // 如果设置了负责人或经办人，检查是否有从公海领取客户的权限
          if ((hasCaseHandler || hasHandlerUser) && !this.checkPermission(['system:pool:claim'])) {
            this.$modal.msgError("您没有从公海领取客户的权限");
            return;
          }
          
          const now = new Date();
          const formattedDate = now.getFullYear() + '-' +
            String(now.getMonth() + 1).padStart(2, '0') + '-' +
            String(now.getDate()).padStart(2, '0') + ' ' +
            String(now.getHours()).padStart(2, '0') + ':' +
            String(now.getMinutes()).padStart(2, '0') + ':' +
            String(now.getSeconds()).padStart(2, '0');

          // 处理关联人信息
          const names = this.contactPersons.map(p => p.name);
          const phones = this.contactPersons.map(p => p.phone);
          
          // 保持公海类型不变，即使设置了负责人或经办人
          const submitData = {
            ...this.form,
            poolType: this.form.poolType, // 保持公海类型不变
            updateBy: this.$store.state.user.name,
            contactPersonName: JSON.stringify(names),
            contactPersonPhone: JSON.stringify(phones),
            isVisible: hasCaseHandler || hasHandlerUser ? true : false // 如果设置了负责人或经办人，将isVisible设置为true
          };

          console.log('提交的数据:', submitData);

          if (this.form.caseId != null) {
            updateBankCustomerCases(submitData).then(response => {
              if (response.code === 200) {
                // 根据是否设置了负责人或经办人给出不同的提示
                if (hasCaseHandler || hasHandlerUser) {
                  this.$modal.msgSuccess("修改成功，客户已分配负责人");
                } else {
                  this.$modal.msgSuccess("修改成功");
                }
                this.open = false;
                this.getList();
              } else {
                this.$modal.msgError(response.msg || "修改失败");
              }
            }).catch(error => {
              console.error('修改客户信息失败:', error);
              this.$modal.msgError("修改失败，请重试");
            });
          } else {
            addBankCustomerCases(submitData).then(response => {
              if (response.code === 200) {
                this.$modal.msgSuccess("新增成功");
                this.open = false;
                this.getList();
              } else {
                this.$modal.msgError(response.msg || "新增失败");
              }
            }).catch(error => {
              console.error('新增客户信息失败:', error);
              this.$modal.msgError("新增失败，请重试");
            });
          }
        }
      });
    },

    /** 判断是否为JSON数组 */
    isJsonArray(str) {
      if (!str) return false;
      try {
        const obj = JSON.parse(str);
        return Array.isArray(obj);
      } catch (e) {
        return false;
      }
    },
    
    /** 解析关联人信息 */
    parseContactPersons(namesJson, phonesJson) {
      try {
        const names = JSON.parse(namesJson || '[]');
        const phones = JSON.parse(phonesJson || '[]');
        
        return names.map((name, index) => ({
          name,
          phone: phones[index] || ''
        }));
      } catch (e) {
        console.error('解析关联人信息失败:', e);
        return [];
      }
    },
    
    /** 添加关联人 */
    addContactPerson() {
      this.contactPersons.push({ name: '', phone: '' });
    },
    
    /** 删除关联人 */
    removeContactPerson(index) {
      this.contactPersons.splice(index, 1);
    },

    /** 文件上传成功处理 */
    handleUploadSuccess(response, file, fileList) {
      if (response.code === 200) {
        // 如果是新建客户
        if (!this.form.caseId) {
          // 如果已经有文件信息，追加新文件
          if (this.form.fileInfo) {
            this.form.fileInfo = this.form.fileInfo + ';' + response.data;
          } else {
            // 如果还没有文件信息，直接使用新文件
            this.form.fileInfo = response.data;
          }
        } else {
          // 如果是修改客户，追加新文件
          const currentFiles = this.form.fileInfo ? this.form.fileInfo.split(';') : [];
          currentFiles.push(response.data);
          this.form.fileInfo = currentFiles.join(';');
        }
        
        // 更新文件列表显示
        this.fileList = fileList;
        this.updateParsedFileList();
        this.$modal.msgSuccess(response.msg);
      } else {
        this.$modal.msgError(response.msg);
      }
    },

    /** 更新已解析的文件列表 */
    updateParsedFileList() {
      if (!this.form.fileInfo) {
        this.parsedFileList = [];
        return;
      }
      
      // 确保不会处理重复的文件
      const uniqueFiles = new Set(this.form.fileInfo.split(';'));
      this.parsedFileList = Array.from(uniqueFiles).map(fileInfo => {
        const parts = fileInfo.split('|');
        return {
          name: parts[0],
          path: parts[1],
          fullInfo: fileInfo
        };
      });

      // 更新form中的fileInfo，确保没有重复项
      this.form.fileInfo = Array.from(uniqueFiles).join(';');
    },

    /** 文件删除处理 */
    handleFileDelete(index) {
      this.$modal.confirm('是否确认删除该文件？').then(() => {
        const files = this.form.fileInfo.split(';');
        files.splice(index, 1);
        this.form.fileInfo = files.join(';');
        this.updateParsedFileList();
        this.$modal.msgSuccess("删除成功");
      }).catch(() => {});
    },

    /** 文件移除处理 */
    handleFileRemove(file, fileList) {
      // 从parsedFileList中找到对应的文件信息
      const removedFile = this.parsedFileList.find(f => f.name === file.name);
      if (removedFile) {
        // 从fileInfo中移除该文件
        const files = this.form.fileInfo.split(';').filter(f => f !== removedFile.fullInfo);
        this.form.fileInfo = files.join(';');
        this.updateParsedFileList();
      }
      this.fileList = fileList;
    },

    /** 文件上传失败处理 */
    handleUploadError(error) {
      this.$modal.msgError("上传失败，请重试");
    },

    /** 文件上传前的处理 */
    handleBeforeUpload(file) {
      const isLt500M = file.size / 1024 / 1024 < 500;
      if (!isLt500M) {
        this.$modal.msgError('上传文件大小不能超过 500MB!');
        return false;
      }
      return true;
    },

    /** 获取原始文件名 */
    getOriginalFileName(fileInfo) {
      if (!fileInfo) return '';
      const parts = fileInfo.split('|');
      return parts[0] || '';
    },

    /** 获取存储路径 */
    getStoragePath(fileInfo) {
      if (!fileInfo) return '';
      const parts = fileInfo.split('|');
      return parts[1] || '';
    },

    /** 下载单个文件 */
    handleDownload(file) {
      const baseUrl = process.env.VUE_APP_BASE_API;
      const token = getToken();
      const url = baseUrl + "/system/cases/download-file?filePath=" + encodeURIComponent(file.path);
      
      const xhr = new XMLHttpRequest();
      xhr.open("GET", url, true);
      xhr.responseType = "blob";
      xhr.setRequestHeader("Authorization", "Bearer " + token);
      
      xhr.onload = () => {
        if (xhr.status === 200) {
          const blob = new Blob([xhr.response]);
          if (window.navigator.msSaveOrOpenBlob) {
            navigator.msSaveBlob(blob, file.name);
          } else {
            const url = window.URL.createObjectURL(blob);
            const link = document.createElement("a");
            link.href = url;
            link.setAttribute("download", file.name);
            document.body.appendChild(link);
            link.click();
            document.body.removeChild(link);
            window.URL.revokeObjectURL(url);
          }
        } else {
          this.$modal.msgError("下载失败");
        }
      };
      
      xhr.onerror = () => {
        this.$modal.msgError("下载失败");
      };
      
      xhr.send();
    },

    /** 处理时间范围变化 */
    handleTimeRangeChange(range) {
      const now = new Date();
      let startDate = new Date();
      let endDate = new Date();
      
      switch (range) {
        case 'week':
          // 获取本周的周一和周日
          const day = now.getDay() || 7; // 如果是周日(0)，将其视为7
          startDate = new Date(now); // 本周一
          endDate = new Date(now);   // 本周日
          startDate.setDate(now.getDate() - (day - 1)); // 设置为本周一
          endDate.setDate(startDate.getDate() + 6);     // 设置为本周日
          break;
        case 'month':
          // 设置为本月初和本月末
          startDate = new Date(now.getFullYear(), now.getMonth(), 1);
          endDate = new Date(now.getFullYear(), now.getMonth() + 1, 0);
          break;
        case 'quarter':
          // 设置为本季度初和本季度末
          const quarterMonth = Math.floor(now.getMonth() / 3) * 3;
          startDate = new Date(now.getFullYear(), quarterMonth, 1);
          endDate = new Date(now.getFullYear(), quarterMonth + 3, 0);
          break;
        case 'year':
          // 设置为本年初和本年末
          startDate = new Date(now.getFullYear(), 0, 1);
          endDate = new Date(now.getFullYear(), 11, 31);
          break;
        case 'custom':
          // 自定义时间范围，不做处理
          return;
        default:
          // 默认不设置时间范围
          this.queryParams.beginTime = null;
          this.queryParams.endTime = null;
          this.getStatistics();
          return;
      }

      // 设置时间为当天的开始和结束
      startDate.setHours(0, 0, 0, 0);
      endDate.setHours(23, 59, 59, 999);

      this.queryParams.beginTime = this.parseTime(startDate, '{y}-{m}-{d}');
      this.queryParams.endTime = this.parseTime(endDate, '{y}-{m}-{d}');
      
      // 添加调试日志
      console.log('设置时间范围:', {
        beginTime: this.queryParams.beginTime,
        endTime: this.queryParams.endTime,
        range: range
      });
      
      // 确保 params 对象中也包含时间参数
      if (!this.queryParams.params) {
        this.queryParams.params = {};
      }
      this.queryParams.params.beginTime = this.queryParams.beginTime;
      this.queryParams.params.endTime = this.queryParams.endTime;
      
      this.getStatistics();
    },

    /** 处理自定义日期变化 */
    handleCustomDateChange(dates) {
      if (dates) {
        this.queryParams.beginTime = dates[0];
        this.queryParams.endTime = dates[1];
        
        // 确保 params 对象中也包含时间参数
        if (!this.queryParams.params) {
          this.queryParams.params = {};
        }
        this.queryParams.params.beginTime = this.queryParams.beginTime;
        this.queryParams.params.endTime = this.queryParams.endTime;
      } else {
        this.queryParams.beginTime = null;
        this.queryParams.endTime = null;
        if (this.queryParams.params) {
          this.queryParams.params.beginTime = null;
          this.queryParams.params.endTime = null;
        }
      }
      
      this.getStatistics();
    },

    /** 计算百分比 */
    calculatePercentage(count) {
      if (!this.periodStats.total) return '0';
      return ((count / this.periodStats.total) * 100).toFixed(1);
    },

    /** 获取标签类型 */
    getTagType(poolType) {
      const types = ['success', 'warning', 'danger', 'info', 'primary'];
      return types[poolType % types.length] || 'primary';
    },

    /** 获取字典标签 */
    getDictLabel(value) {
      const dictData = this.dict.type.pool_type;
      const item = dictData.find(dict => dict.value === value);
      return item ? item.label : value;
    },

    /** 判断日期是否在选择的时间范围内 */
    isInTimeRange(dateStr) {
      if (!dateStr) return false;
      
      // 如果没有设置时间范围，返回true
      if (!this.queryParams.beginTime || !this.queryParams.endTime) {
        return true;
      }
      
      try {
        const date = new Date(dateStr);
        const beginTime = new Date(this.queryParams.beginTime);
        const endTime = new Date(this.queryParams.endTime);
        
        // 确保日期有效
        if (isNaN(date.getTime()) || isNaN(beginTime.getTime()) || isNaN(endTime.getTime())) {
          console.warn('无效的日期格式:', { dateStr, beginTime: this.queryParams.beginTime, endTime: this.queryParams.endTime });
          return false;
        }
        
        // 设置时间为当天的开始和结束
        beginTime.setHours(0, 0, 0, 0);
        endTime.setHours(23, 59, 59, 999);
        
        const result = date >= beginTime && date <= endTime;
        console.log('日期比较结果:', {
          date: dateStr,
          beginTime: this.queryParams.beginTime,
          endTime: this.queryParams.endTime,
          isInRange: result
        });
        
        return result;
      } catch (error) {
        console.error('日期比较出错:', error);
        return false;
      }
    },

    /** 分页大小改变 */
    handleSizeChange(val) {
      this.queryParams.pageSize = val;
      this.getList();
    },

    /** 分页页码改变 */
    handleCurrentChange(val) {
      this.queryParams.pageNum = val;
      this.getList();
    },

    /** 获取公海池卡片样式 */
    getPoolCardClass(type) {
      const classes = {
        '1': 'unassigned-pool',    // 未分配客户
        '2': 'litigation-pool',    // 司法诉讼中
        '3': 'case-pool',          // 已立案客户
        '4': 'resolved-pool',      // 已调解客户
        '5': 'judgment-pool',      // 已判决客户
        '6': 'enforcement-pool'    // 强制执行中
      };
      return classes[type] || 'default-pool';
    },

    /** 获取公海池图标 */
    getPoolIcon(type) {
      const icons = {
        '1': 'el-icon-user',          // 未分配客户
        '2': 'el-icon-document',      // 司法诉讼中
        '3': 'el-icon-folder-opened', // 已立案客户
        '4': 'el-icon-chat-round',    // 已调解客户
        '5': 'el-icon-document-checked', // 已判决客户
        '6': 'el-icon-warning',       // 强制执行中
        '7': 'el-icon-check',         // 已清偿客户
        '8': 'el-icon-alarm-clock'    // 暂时搁置
      };
      return icons[type] || 'el-icon-office-building';
    },

    /** 获取公海池标签类型 */
    getPoolTagType(type) {
      const types = {
        '1': 'danger',    // 未分配客户 - 红色
        '2': 'warning',   // 司法诉讼中 - 橙色
        '3': 'primary',   // 已立案客户 - 蓝色
        '4': 'success',   // 已调解客户 - 绿色
        '5': 'info',      // 已判决客户 - 灰色
        '6': 'danger',    // 强制执行中 - 红色
        '7': 'success',   // 已清偿客户 - 绿色
        '8': 'info'       // 暂时搁置 - 灰色
      };
      return types[type] || 'primary';
    },

    /** 检查权限 */
    checkPermission(permissions) {
      const all_permission = "*:*:*";
      const userPermissions = this.$store.getters && this.$store.getters.permissions;
      
      if (userPermissions) {
        return userPermissions.some(p => {
          return all_permission === p || permissions.includes(p);
        });
      }
      return false;
    },
  },
  watch: {
    casesList: {
      handler(newVal) {
        if (newVal && newVal.length > 0) {
          this.$nextTick(() => {
            // 每行高度约为37px，表头高度为40px
            this.tableHeight = newVal.length * 37 + 40;
          });
        } else {
          this.tableHeight = 80;
        }
      },
      immediate: true
    },
  }
};
</script>

<style scoped>
.app-container {
  position: absolute;
  top: 50px; /* 减小顶部位置，避免顶部白条 */
  left: 0;
  right: 0;
  bottom: 0;
  padding: 0 5px 0 5px; /* 移除顶部内边距 */
  margin-top: -50px; /* 使用负边距向上移动整个容器 */
  background-color: #f0f2f5;
  overflow: hidden;
  display: flex;
  flex-direction: column;
  z-index: 100;
  margin-left: 0;
  margin-right: 0;
  margin-bottom: 0;
  border: none;
}

.h-100 {
  height: 100%;
}

.el-row {
  margin: 0 -5px !important;
  width: calc(100% + 10px);
  height: 100% !important;
}
/*公海池类型导航组件*/
.left-panel {
  background-color: #fff;
  height: 100%;
  border-radius: 0;
  box-shadow: 0 2px 12px rgba(0, 21, 41, 0.08);
  display: flex;
  flex-direction: column;
  overflow: hidden;
}

.right-panel {
  background-color: #fff;
  height: 100%;
  padding: 3px;
  padding-bottom: 0;
  border-radius: 16px 16px 0 0;
  box-shadow: 0 1px 4px rgba(0, 21, 41, 0.08);
  display: flex;
  flex-direction: column;
  overflow: hidden;
}

.scroll-container {
  flex: 1;
  overflow-y: auto;
  overflow-x: hidden;
  padding-right: 5px;
  padding-bottom: 0;
  display: flex;
  flex-direction: column;
  margin-bottom: 0;
}

.panel-title {
  padding: 15px;
  font-size: 16px;
  font-weight: bold;
  border-bottom: 1px solid #ebeef5;
  background: linear-gradient(to right, #f2f6fc, #ffffff);
  display: flex;
  align-items: center;
}

.panel-title i {
  margin-right: 10px;
  font-size: 18px;
  color: #409EFF;
}

.panel-content {
  flex: 1;
  overflow-y: auto;
  padding: 8px 0;
}

.pool-menu {
  border-right: none;
  background-color: transparent;
}

.pool-menu-item {
  height: 50px !important;
  line-height: 50px !important;
  padding: 0 15px !important;
  border-radius: 12px;
  margin: 4px 8px !important;
  transition: all 0.3s;
}

.menu-item-content {
  display: flex;
  justify-content: space-between;
  align-items: center;
  width: 100%;
}

.menu-item-left {
  display: flex;
  align-items: center;
  overflow: hidden;
}

.menu-item-icon {
  font-size: 16px;
  margin-right: 10px;
  width: 24px;
  height: 24px;
  display: flex;
  align-items: center;
  justify-content: center;
  border-radius: 8px;
  background-color: rgba(64, 158, 255, 0.1);
  color: #409EFF;
  transition: all 0.3s;
}

.menu-item-label {
  font-size: 14px;
  white-space: nowrap;
  overflow: hidden;
  text-overflow: ellipsis;
}

.pool-menu .el-menu-item.is-active {
  background-color: #ecf5ff !important;
  color: #409EFF;
  font-weight: bold;
}

.pool-menu .el-menu-item.is-active .menu-item-icon {
  background-color: #409EFF;
  color: #fff;
}

.pool-menu .el-menu-item:hover {
  background-color: #f5f7fa !important;
}

.pool-menu .el-menu-item:hover .menu-item-icon {
  transform: scale(1.1);
}
/*公海池卡片样式字体大小*/
.pool-count {
  margin-left: 8px;
  font-weight: bold;
  background-color: transparent !important;
  border: none !important;
  padding: 0 !important;
  font-size: 16px !important;
}

.search-section {
  flex-shrink: 0;
  background-color: #fafafa;
  padding: 2px;
  border-radius: 4px;
  margin-bottom: 2px;
}

.table-container {
  flex: 1;
  min-height: auto;
  display: flex;
  flex-direction: column;
  overflow: hidden;
  margin-bottom: 0;
}

.el-table {
  flex: 1;
  overflow: hidden;
}

.el-table__body-wrapper {
  overflow-y: auto !important;
}

.pagination-container {
  flex-shrink: 0;
  padding: 0;
  background: #fff;
  margin-top: 0;
  margin-bottom: 0;
}

/* 输入框样式优化 */
.el-input__inner {
  border-radius: 4px;
  height: 28px;
  line-height: 28px;
}

/* 表格内标签样式 */
.el-tag {
  border-radius: 2px;
  padding: 0 4px;
  height: 20px;
  line-height: 18px;
}

/* 分配对话框样式 */
.el-dialog {
  border-radius: 8px;
}

.el-dialog__header {
  padding: 20px;
  border-bottom: 1px solid #ebeef5;
}

.el-dialog__body {
  padding: 30px 20px;
}

.el-dialog__footer {
  padding: 20px;
  border-top: 1px solid #ebeef5;
}

.statistics-section {
  flex-shrink: 0;
  margin-bottom: 16px;
}

.statistics-card {
  background: #fff;
  border-radius: 16px;
  margin-bottom: 20px;
  box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.05);
  overflow: hidden;
}

.statistics-card:last-child {
  margin-bottom: 0;
}

.statistics-header {
  padding: 16px 20px;
  border-bottom: 1px solid #f0f2f5;
  display: flex;
  align-items: center;
  justify-content: space-between;
  background: linear-gradient(to right, #f8f9fa, #fff);
}

.left-section {
  display: flex;
  align-items: center;
  gap: 24px;
}

.statistics-title {
  font-size: 16px;
  font-weight: 600;
  color: #1f2f3d;
  display: flex;
  align-items: center;
  gap: 8px;
}

.statistics-title i {
  font-size: 20px;
  background: linear-gradient(135deg, #409EFF, #67C23A);
  -webkit-background-clip: text;
  -webkit-text-fill-color: transparent;
}

.statistics-body {
  padding: 20px;
}

.time-text {
  text-align: center;
  margin-top: 8px;
  color: #606266;
  font-size: 13px;
}

.stat-card {
  height: 100%;
  padding: 24px;
  border-radius: 16px;
  display: flex;
  align-items: flex-start;
  gap: 16px;
  transition: all 0.3s ease;
  position: relative;
  overflow: hidden;
  box-shadow: 0 2px 6px rgba(0, 0, 0, 0.03);
}

.stat-card::before {
  content: '';
  position: absolute;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  opacity: 0.03;
  transition: opacity 0.3s ease;
}

.total-card {
  background: linear-gradient(135deg, #f0f9ff 0%, #ffffff 100%);
  border-left: 3px solid #93c5fd;
}

.total-card::before {
  background: linear-gradient(135deg, #93c5fd, #a7f3d0);
  opacity: 0.05;
}

.rate-card {
  background: linear-gradient(135deg, #f0fdf4 0%, #ffffff 100%);
  border-left: 3px solid #86efac;
}

.rate-card::before {
  background: linear-gradient(135deg, #86efac, #93c5fd);
  opacity: 0.05;
}

.stat-card:hover::before {
  opacity: 0.06;
}

.stat-icon {
  position: relative;
  z-index: 1;
  width: 48px;
  height: 48px;
  border-radius: 50%;
  display: flex;
  align-items: center;
  justify-content: center;
  font-size: 22px;
  color: #ffffff;
  box-shadow: 0 4px 8px rgba(0, 0, 0, 0.05);
}

.total-card .stat-icon {
  background-color: #60a5fa;
}

.rate-card .stat-icon {
  background-color: #4ade80;
}

.stat-info {
  position: relative;
  z-index: 1;
  flex: 1;
}

.stat-label {
  font-size: 14px;
  color: #606266;
  margin-bottom: 8px;
  font-weight: 500;
}

.stat-value {
  font-size: 28px;
  font-weight: 600;
  color: #334155;
  margin-bottom: 6px;
  line-height: 1.2;
}

.pool-stat-card {
  background: #ffffff;
  border-radius: 16px;
  padding: 20px;
  margin-bottom: 16px;
  display: flex;
  align-items: center;
  gap: 16px;
  cursor: pointer;
  transition: all 0.3s ease;
  position: relative;
  overflow: hidden;
  border-left-width: 3px;
  border-left-style: solid;
  box-shadow: 0 2px 6px rgba(0, 0, 0, 0.03);
}

.pool-stat-card:hover {
  transform: translateY(-2px);
  box-shadow: 0 4px 12px rgba(0, 0, 0, 0.05);
}

.pool-stat-icon {
  width: 42px;
  height: 42px;
  border-radius: 12px;
  display: flex;
  align-items: center;
  justify-content: center;
  font-size: 20px;
  position: relative;
  z-index: 1;
  box-shadow: 0 3px 6px rgba(0, 0, 0, 0.05);
}

.pool-stat-info {
  flex: 1;
  position: relative;
  z-index: 1;
}

.pool-stat-label {
  font-size: 15px;
  color: #1f2f3d;
  margin-bottom: 8px;
  font-weight: 500;
}

.pool-stat-value {
  font-size: 26px;
  font-weight: 600;
  margin-bottom: 4px;
  color: #334155;
}

.pool-stat-desc {
  font-size: 13px;
  color: #909399;
}

.unassigned-pool {
  background: linear-gradient(135deg, #fef2f2 0%, #ffffff 100%);
  border-left-color: #fca5a5;
}
.unassigned-pool::before {
  background: linear-gradient(135deg, #fca5a5, #f87171);
}
.unassigned-pool .pool-stat-icon {
  color: #ffffff;
  background-color: #fca5a5;
}

.litigation-pool {
  background: linear-gradient(135deg, #eff6ff 0%, #ffffff 100%);
  border-left-color: #93c5fd;
}
.litigation-pool::before {
  background: linear-gradient(135deg, #93c5fd, #60a5fa);
}
.litigation-pool .pool-stat-icon {
  color: #ffffff;
  background-color: #60a5fa;
}

.case-pool {
  background: linear-gradient(135deg, #f0fdf4 0%, #ffffff 100%);
  border-left-color: #86efac;
}
.case-pool::before {
  background: linear-gradient(135deg, #86efac, #4ade80);
}
.case-pool .pool-stat-icon {
  color: #ffffff;
  background-color: #4ade80;
}

.resolved-pool {
  background: linear-gradient(135deg, #f0fdfa 0%, #ffffff 100%);
  border-left-color: #5eead4;
}
.resolved-pool::before {
  background: linear-gradient(135deg, #5eead4, #2dd4bf);
}
.resolved-pool .pool-stat-icon {
  color: #ffffff;
  background-color: #2dd4bf;
}

.judgment-pool {
  background: linear-gradient(135deg, #fffbeb 0%, #ffffff 100%);
  border-left-color: #fcd34d;
}
.judgment-pool::before {
  background: linear-gradient(135deg, #fcd34d, #fbbf24);
}
.judgment-pool .pool-stat-icon {
  color: #ffffff;
  background-color: #fbbf24;
}

.enforcement-pool {
  background: linear-gradient(135deg, #fef2f2 0%, #ffffff 100%);
  border-left-color: #fca5a5;
}
.enforcement-pool::before {
  background: linear-gradient(135deg, #fca5a5, #f87171);
}
.enforcement-pool .pool-stat-icon {
  color: #ffffff;
  background-color: #fca5a5;
}

.default-pool {
  background: linear-gradient(135deg, #f8fafc 0%, #ffffff 100%);
  border-left-color: #cbd5e1;
}
.default-pool::before {
  background: linear-gradient(135deg, #cbd5e1, #94a3b8);
}
.default-pool .pool-stat-icon {
  color: #ffffff;
  background-color: #94a3b8;
}

.card-time-text {
  font-size: 13px;
  color: #8c9cb8;
  margin-top: 10px;
  background-color: #f2f6fc;
  padding: 6px 0;
  text-align: center;
  border-radius: 4px;
  width: 100%;
}

/* 移除之前添加的时间范围栏样式 */
.date-range-bar {
  display: none;
}

/* 全局修改，移除底部间距 */
html, body {
  margin: 0;
  padding: 0;
  overflow: hidden;
}

/* 关联人信息编辑器样式 */
.contact-persons-editor-simple {
  border-top: 1px solid #f0f0f0;
  padding-top: 10px;
}

.contact-person-row {
  display: flex;
  align-items: center;
  margin-bottom: 5px;
}

.add-contact-simple {
  margin-top: 5px;
  text-align: left;
  border-top: 1px dashed #f0f0f0;
  padding-top: 8px;
}

/* 文件列表样式 */
.upload-demo {
  margin-bottom: 10px;
}

.el-upload__tip {
  line-height: 1.2;
  color: #909399;
  font-size: 12px;
}

.existing-files {
  margin-top: 10px;
}

.file-item {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 5px 0;
  border-bottom: 1px solid #EBEEF5;
}

.file-name {
  flex: 1;
  overflow: hidden;
  text-overflow: ellipsis;
  white-space: nowrap;
}

.file-actions {
  margin-left: 10px;
}

/* 表单对话框标签样式 */
.el-dialog .el-form-item__label {
  font-weight: 700 !important;
  color: #000000 !important;
  font-size: 14px !important;
}

/* 为标签添加下划线效果 */
.el-dialog .el-form-item__label::after {
  content: "";
  display: block;
  width: 90%;
  height: 2px;
  background-color: #409EFF;
  position: absolute;
  bottom: 0;
  left: 0;
  transform: scaleX(0);
  transition: transform 0.3s;
}

.el-dialog .el-form-item:hover .el-form-item__label::after {
  transform: scaleX(1);
}

/* 公海池退出提示样式 */
.pool-exit-tip {
  margin-bottom: 16px;
}

.pool-exit-tip .el-alert {
  border-radius: 4px;
}

.pool-exit-tip .el-alert__title {
  font-size: 15px;
  font-weight: 600;
}

.pool-exit-tip .el-alert__content {
  padding: 8px 0;
}

.pool-exit-tip strong {
  color: #409EFF;
  font-weight: 700;
  text-decoration: underline;
}

.permission-warning {
  margin-top: 10px;
  color: #E6A23C;
  font-size: 12px;
}
</style> 